<?php
/**
 * User: Feng
 * Date: 2024/08/03
 */

namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\Navigation;

class Resource extends Manage
{
	public function lists()
	{
		if ($this->request->isAjax()) {
			return (new \app\common\model\Resource())->tableData(input('param.'));
		}
		$navLists = (new Navigation())->field('id, title')->all();
		return $this->fetch('lists', ['navLists' => $navLists]);
	}

	public function add()
	{
		if ($this->request->isPost()) {
			return (new \app\common\model\Resource())->addData(input('param.'));
		}
		$navLists = (new Navigation())->field('id, title')->all();
		return $this->fetch('add', ['navLists' => $navLists]);
	}

	public function edit()
	{
		if ($this->request->isPost()) {
			$data = [
				'id'       => input('post.id'),
				'nav_id'   => input('post.nav_id'),
				'title'    => input('post.title'),
				'is_top'   => input('post.is_top'),
				'is_index' => input('post.is_index'),
				'brief'    => input('post.brief'),
				'pic'      => input('post.pic'),
				'content'  => input('post.content', '', 'safe_filter'),
			];
			return (new \app\common\model\Resource())->saveData($data);
		}
		$info = (new \app\common\model\Resource())->get(input('param.id/d'));
		if (! $info) {
			return error_code(10002);
		}
		$navLists = (new Navigation())->field('id, title')->all();
		return $this->fetch('edit', [
			'info'     => $info,
			'navLists' => $navLists
		]);
	}

	public function recommend()
	{
		if ($this->request->isPost()) {
			$resource_ids = input('resource_id/a', []);
			$data = [
				'id'        => input('post.id'),
				'title'     => input('post.title'),
				'recommend' => $resource_ids,
			];
			return (new \app\common\model\Resource())->saveData($data);
		}
		$info = (new \app\common\model\Resource())->get(input('param.id/d'));
		$recommend = json_decode($info['recommend']);
		if (! $info) {
			return error_code(10002);
		}
		$recommendLists = (new \app\common\model\Resource())->where(['nav_id' => $info['nav_id']])->field('id, title')->all();
		return $this->fetch('recommend', [
			'info'      => $info,
			'recommend' => $recommend,
			'recLists'  => $recommendLists
		]);
	}

	public function del()
	{
		$result = [
			'status' => true,
			'msg'    => '删除成功',
			'data'   => ''
		];
		if (! (new \app\common\model\Resource())->where(['id' => input('param.id/d')])->delete()) {
			return error_code(10023);
		}
		return $result;
	}
}